// static/user/js/modules/payment.js
class PaymentManager {
    constructor() {
        this.modal = document.getElementById('paymentModal');
        this.maskLayer = document.getElementById('globalMaskLayer');;
        this.selectedMethod = null;
        this.cartIds = [];
        this.itemIds = [];

        // 安全检查
        if (!this.modal || !this.maskLayer) {
            console.error('支付弹窗或遮罩层元素未找到');
            return;
        }

        this.init();
    }

    async init() {
        this.bindEvents();
    }

    async showPaymentModal() {
        try {
            // 获取选中金额
            const amountData = await fetchData(API.ORDER.GET_AMOUNT);

            // 计算总金额
            const total = parseFloat(amountData.amount) + parseFloat(amountData.deposit);

            // 更新金额显示
            document.getElementById('orderAmount').textContent = `¥${amountData.amount}`;
            document.getElementById('depositAmount').textContent = `¥${amountData.deposit}`;
            document.getElementById('totalAmount').textContent = `¥${total.toFixed(2)}`;

            // 显示弹窗
            this.modal.classList.add('active');
            MaskLayer.show();
        } catch (error) {
            Alert.show(error.message, 'error');
        }
    }

    bindEvents() {
        // 关闭按钮安全绑定
        const closeBtn = this.modal.querySelector('.py-close-btn');
        if (closeBtn) {
            closeBtn.addEventListener('click', () => this.close());
        }

        // 遮罩层安全绑定
        if (this.maskLayer) {
            this.maskLayer.addEventListener('click', (e) => {
                if (e.target === this.maskLayer) {
                    this.close();
                }
            });
        }

        // 选择支付方式
        document.querySelectorAll('.payment-method').forEach(item => {
            item.addEventListener('click', () => {
                document.querySelectorAll('.payment-method').forEach(i => i.classList.remove('active'));
                item.classList.add('active');
                this.selectedMethod = item.dataset.type;
                document.getElementById('confirmPayment').disabled = false;
            });
        });

        // 确认支付
        document.getElementById('confirmPayment').addEventListener('click', async () => {
            try {
                const selectedItems = Array.from(document.querySelectorAll('.cart-item input[type="checkbox"]:checked'));

                const carts = selectedItems.map(item => {
                    const cartItem = item.closest('.cart-item');
                    return {
                        cartId: cartItem.dataset.cartId,
                        dailyRate: parseFloat(cartItem.querySelector('.cart-item__price').textContent.replace('¥', '')),
                        quantity: cartItem.querySelector('.quantity-input').value
                    };
                });

                const result = await fetchResponse(API.ORDER.CREATE, {
                    carts
                });

                if (result.code === 0) {
                    this.close();
                    const cartManager = new CartManager();
                    cartManager.closeDrawer();
                    Alert.show(result.msg, 'success');
                } else {
                    Alert.show(result.msg, 'error');
                }
            } catch (error) {
                Alert.show(error.message, 'error');
            }
        });
    }

    close() {
        this.modal.classList.remove('active');
        MaskLayer.hide();
        this.selectedMethod = null;
        document.getElementById('confirmPayment').disabled = true;
    }
}

// 修改初始化方式（在DOM加载完成后）
document.addEventListener('DOMContentLoaded', () => {
    window.paymentManager = new PaymentManager(); // 暴露到全局便于调试
});